//
//  PropertySeriviceViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/7/17.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "PropertySeriviceViewController.h"

@interface PropertySeriviceViewController () <UITableViewDelegate,UITableViewDataSource,PostImgTableViewCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>

@property (strong, nonatomic) UITableView * tableview;
@property (strong, nonatomic) NSMutableArray * imgArr;
@property (strong, nonatomic) NSMutableArray * selectedAssets;
@property (strong, nonatomic) CLLocation *location;
@property (nonatomic,copy) NSString * name;
@property (nonatomic,copy) NSString * tel;
@property (nonatomic,copy) NSString * address;
@property (nonatomic,copy) NSString * requestStr;
@property (nonatomic,copy) NSString * content;
@property (strong, nonatomic) TypeModel * selectModel;

@end

@implementation PropertySeriviceViewController

static NSString * cellID = @"cell";
static NSString * PropertyReparisInputInfoTableViewCellID = @"PropertyReparisInputInfoTableViewCell";
static NSString * PropertyReparisTextViewTableViewCellID = @"PropertyReparisTextViewTableViewCell";
static NSString * PostImgTableViewCellID = @"PostImgTableViewCell";
static NSString * PropertyReairsCommitTableViewCellID = @"PropertyReairsCommitTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"客服中心";
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [btn setImage:[UIImage imageNamed:@"PhoneCallImg"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    if (self.complianArr == nil) {
        [self requestComplianTypeData];
    }else
    {
        if (self.complianArr.count) {
            TypeModel * mdoel1 = [self.complianArr firstObject];
            self.selectModel = mdoel1;
        }
    }
    
    [self creatTableview];
    [self registCell];
}

-(void)requestComplianTypeData
{
    WeakSelf;
    NSString * urlStr = [NSString stringWithFormat:@"/rest/tsRecordController/getTsTypeList"];
    [[HTTPClient shareClient] requestWithPath:urlStr AndReturnBlock:^(NSDictionary *dic) {
        NSArray * dataArr = dic[@"data"];
        NSMutableArray * arr = [NSMutableArray array];
        for (NSDictionary * dics in dataArr) {
            TypeModel * mdoel = [TypeModel modelWithDic:dics];
            [arr addObject:mdoel];
        }
        if (arr.count) {
            TypeModel * mdoel1 = [arr firstObject];
            self.selectModel = mdoel1;
        }
        weakSelf.complianArr = arr;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    } AndFailMessage:^(NSString *message, NSString *errorCode) {
        
    }];
}

-(void)rightClick
{
    
}

-(void)registCell
{
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    [self.tableview registerClass:[PropertyReparisInputInfoTableViewCell class] forCellReuseIdentifier:PropertyReparisInputInfoTableViewCellID];
    [self.tableview registerClass:[PropertyReparisTextViewTableViewCell class] forCellReuseIdentifier:PropertyReparisTextViewTableViewCellID];
    [self.tableview registerClass:[PostImgTableViewCell class] forCellReuseIdentifier:PostImgTableViewCellID];
    [self.tableview registerClass:[PropertyReairsCommitTableViewCell class] forCellReuseIdentifier:PropertyReairsCommitTableViewCellID];
}

-(NSMutableArray *)imgArr
{
    if (_imgArr == nil) {
        _imgArr = [NSMutableArray array];
    }
    return _imgArr;
}

-(NSMutableArray *)selectedAssets
{
    if (_selectedAssets == nil) {
        _selectedAssets = [NSMutableArray array];
    }
    return _selectedAssets;
}

-(void)creatTableview{
    if (self.tableview == nil) {
        UITableView * tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH) style:UITableViewStylePlain];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.backgroundColor = SFMWhiteColor;
        if (@available(iOS 11.0, *)) {
            tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
        self.tableview = tableview;
        [self.view addSubview:self.tableview];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 10)];
        line.backgroundColor = SFM242;
        return line;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 4) {
            return 130;
        }
        return 55;
    }else
    {
        if (indexPath.row == 0) {
            return 150;
        }else if(indexPath.row == 1)
        {
            return ((WIDTH - 75)/4 + 15) * (self.imgArr.count / 4 + 1);
        }else
        {
            return 130;
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    }else
    {
        return 3;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 4) {
            WeakSelf;
            PropertyReparisTextViewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PropertyReparisTextViewTableViewCellID];
            cell.placeLabel.text = @"请输入您的投诉要求";
            cell.PropertyReparisTextViewTableViewCellInpuEventBlock = ^(NSString *text) {
                weakSelf.requestStr = text;
            };
            return cell;
        }else
        {
            WeakSelf;
            PropertyReparisInputInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PropertyReparisInputInfoTableViewCellID];
            if (indexPath.row == 0) {
                cell.titleLabel.text = @"联系人";
                cell.textfiled.placeholder = @"请输入联系人";
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.name = text;
                };
            }else if(indexPath.row == 1)
            {
                cell.titleLabel.text = @"联系电话";
                cell.textfiled.placeholder = @"请输入联系电话";
                cell.textfiled.keyboardType = UIKeyboardTypeNumberPad;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.tel = text;
                };
            }else if(indexPath.row == 2)
            {
                cell.titleLabel.text = @"投诉地点";
                cell.textfiled.placeholder = @"请输入投诉地点";
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    weakSelf.address = text;
                };
            }else
            {
                cell.titleLabel.text = @"投诉类型";
                cell.textfiled.placeholder = @"请选择投诉类型";
                cell.textfiled.enabled = NO;
                cell.PropertyReparisInputInfoTableViewCellInputBlock = ^(NSString *text) {
                    
                };
                cell.textfiled.text = self.selectModel.typeName;
            }
            return cell;
        }
    }else
    {
        if(indexPath.row == 0)
        {
            WeakSelf;
            PropertyReparisTextViewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PropertyReparisTextViewTableViewCellID];
            cell.placeLabel.text = @"您遇到什么问题了？我们将及时为你解决";
            cell.PropertyReparisTextViewTableViewCellInpuEventBlock = ^(NSString *text) {
                weakSelf.content = text;
            };
            return cell;
        }else if (indexPath.row == 1)
        {
            PostImgTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PostImgTableViewCellID];
            [cell sendImgArr:self.imgArr];
            [cell setSelectedAssets:self.selectedAssets];
            cell.delegate = self;
            WeakSelf;
            cell.watchVidowBlock = ^(UIViewController *ctr) {
                [weakSelf presentViewController:ctr animated:YES completion:nil];
            };
            cell.seeImgBlock = ^(NSInteger index) {
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:self->_selectedAssets selectedPhotos:self->_imgArr index:index];
                [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                    self->_imgArr = [NSMutableArray arrayWithArray:photos];
                    self->_selectedAssets = [NSMutableArray arrayWithArray:assets];
                    [self->_tableview reloadData];
                }];
                [weakSelf presentViewController:imagePickerVc animated:YES completion:nil];
            };
            return cell;
        }else
        {
            PropertyReairsCommitTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PropertyReairsCommitTableViewCellID];
            [cell.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.btn setTitle:@"提交" forState:UIControlStateNormal];
            return cell;
        }
    }
}

#pragma mark - 提交
-(void)btnClick:(UIButton *)btn
{
    if (self.name == nil) {
        [MBProgressHUD showMessageWithDelay:@"请输入联系人" delay:2];
        return;
    }
    
    if (self.tel == nil) {
        [MBProgressHUD showMessageWithDelay:@"请输入联系电话" delay:2];
        return;
    }
    
    if (self.address == nil) {
        [MBProgressHUD showMessageWithDelay:@"请输入联系地址" delay:2];
        return;
    }
    
    if (self.requestStr == nil) {
        [MBProgressHUD showMessageWithDelay:@"请输入您的投诉要求" delay:2];
        return;
    }
    
    if (self.content == nil) {
        [MBProgressHUD showMessageWithDelay:@"请输入您遇到的问题" delay:2];
        return;
    }
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setValue:self.address forKey:@"tsdd"];
    [params setValue:self.content forKey:@"tsnr"];
    [params setValue:self.requestStr forKey:@"tsyq"];
    [params setValue:self.selectModel.typecode forKey:@"bxLx"];
    [params setValue:self.name forKey:@"tsrname"];
    [params setValue:self.tel forKey:@"tsrtel"];
    
    [params setValue:[NSString currentTimeAndFormat:@"yyyy-MM-dd"] forKey:@"tsdate"];
    [params setValue:[NSString currentTimeAndFormat:@"HH-mm-ss"] forKey:@"tstime"];

    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.archiver"];
    NSArray * arr =  [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (arr.count) {
        authListModel * model = [arr firstObject];
        [params setValue:model.pkCorp forKey:@"pkCorp"];
        [params setValue:model.pkManagementsecid forKey:@"pkManagementsecid"];
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    WeakSelf;
    btn.userInteractionEnabled = NO;
    
    NSString * url = [BASE_URL stringByAppendingString:@"/rest/wxRecordController/saveWxRecord"];
    NSString * path1 = [url stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"*/*" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:SFMToken forHTTPHeaderField:@"X-AUTH-TOKEN"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html", nil];
    
    [manager POST:path1 parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        BOOL isVideo = NO;
        
        for (int i = 0; i<self.selectedAssets.count; i++) {
            NSString * name = [NSString stringWithFormat:@"bxFj%d",i+1];
            id asset = weakSelf.selectedAssets[i];
            if ([asset isKindOfClass:[PHAsset class]]) {
                PHAsset *phAsset = asset;
                isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
            } else if ([asset isKindOfClass:[ALAsset class]]) {
                ALAsset * alAsset = asset;
                isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
            }
            if(isVideo)
            {
//                if (weakSelf.videoStr != nil) {
//                    NSError * error;
//                    [formData appendPartWithFileURL:[NSURL fileURLWithPath:weakSelf.videoStr] name:name fileName:@"fj.mp4" mimeType:@"application/octet-stream" error:&error];
//                    //                @"video/mp4"
//                }
            }else
            {
                NSData * data;
                UIImage * image = [self.imgArr objectAtIndex:i];
                if (UIImagePNGRepresentation(image) != nil)
                {
                    data = UIImageJPEGRepresentation([UIImage newTry:image], qualityNum);
                }else
                {
                    data = UIImageJPEGRepresentation(image, qualityNum);
                }
                if (data!=nil) {
                    [formData appendPartWithFileData:data name:name fileName:name mimeType:@"image/jpeg"];
                }
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = (NSDictionary *)responseObject;
        NSString * codeStr = [NSString stringWithFormat:@"%@",dic[@"respCode"]];
        if ([codeStr isEqualToString:@"0"]) {
            [SVProgressHUD ShowSuccessMessage:@"投诉成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }else
        {
            [SVProgressHUD ShowErrorMessage:dic[@"respMsg"]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            btn.userInteractionEnabled = YES;
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            btn.userInteractionEnabled = YES;
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 3) {
            WeakSelf;
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择保修类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            for (TypeModel * model in self.complianArr) {
                UIAlertAction * action = [UIAlertAction actionWithTitle:model.typeName style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    weakSelf.selectModel = model;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.tableview reloadData];
                    });
                }];
                [alert addAction: action];
            }
            
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction: action1];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

-(BOOL)hidesBottomBarWhenPushed
{
    return YES;
}

-(void)sendPostImgTableViewCellDeleteEvent:(NSInteger)index;
{
    [self deleteBtnClik:index];
}
-(void)sendPostImgTableViewCellAddImgEvent:(NSInteger)index
{
    [self chooseWay];
}

-(void)chooseWay
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    WeakSelf;
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushCtr];
    }];
    
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf takePhoto];
    }];
    
    UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction: action1];
    [alert addAction: action2];
    [alert addAction: action3];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma  mark -开始拍照
- (void)takePhoto {
    WeakSelf;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [self presentViewController:alert animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [weakSelf takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [self presentViewController:alert animated:YES completion:nil];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [weakSelf takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
            [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                [tzImagePickerVc hideProgressHUD];
                TZAssetModel *assetModel = [models firstObject];
                if (tzImagePickerVc.sortAscendingByModificationDate) {
                    assetModel = [models lastObject];
                    [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
                }
            }];
        }];
    }else if ([type isEqualToString:@"public.movie"]) {
        NSURL *videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
        if (videoUrl) {
            [[TZImageManager manager] saveVideoWithUrl:videoUrl location:self.location completion:^(PHAsset *asset, NSError *error) {
                if (!error) {
                    [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:NO needFetchAssets:NO completion:^(TZAlbumModel *model) {
                        [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:YES allowPickingImage:NO completion:^(NSArray<TZAssetModel *> *models) {
                            [tzImagePickerVc hideProgressHUD];
                            TZAssetModel *assetModel = [models firstObject];
                            if (tzImagePickerVc.sortAscendingByModificationDate) {
                                assetModel = [models lastObject];
                            }
                            [[TZImageManager manager] getPhotoWithAsset:assetModel.asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                                if (!isDegraded && photo) {
                                    [self refreshCollectionViewWithAddedAsset:assetModel.asset image:photo];
                                }
                            }];
                        }];
                    }];
                } else {
                    [tzImagePickerVc hideProgressHUD];
                }
            }];
        }
    }
}

- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    [self.imgArr addObject:image];
    [self.selectedAssets addObject:asset];
    [self.tableview reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)deleteBtnClik:(NSInteger)index
{
    [self.imgArr removeObjectAtIndex:index];
    [self.selectedAssets removeObjectAtIndex:index];
    [self.tableview reloadData];
}

-(void)pushCtr
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.selectedAssets = self.selectedAssets; // 目前已经选中的图片数组
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    [self.tableview reloadData];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    self.imgArr = [NSMutableArray arrayWithArray:photos];
    self.selectedAssets = [NSMutableArray arrayWithArray:assets];
    [self.tableview reloadData];
}

// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    return YES;
}

// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    return YES;
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    _imgArr = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    // open this code to send video / 打开这段代码发送视频
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPreset640x480 success:^(NSString *outputPath) {
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        // Export completed, send video here, send by outputPath or NSData
        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
    [self.tableview reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
